package com.bytedance.danmaku.render.engine.demo.utils

import com.bytedance.danmaku.render.engine.BaseDanmakuData

/**
 * @Description:
 * @Author yanxin
 * @Date:  2025/9/24
 */

class DanmakuDataProcessor(
    private val videoDurationMs: Long,
    private val windowMs: Long = 3000L
) {
    private val danmakuPool = mutableListOf<BaseDanmakuData>() // 已加载的弹幕池
    private val displayedIds = mutableSetOf<String>() // 已显示过的弹幕ID

    /**
     * 初次加载弹幕数据
     */
    fun loadInitialData(danmakus: List<BaseDanmakuData>) {
        danmakuPool.clear()
        danmakuPool.addAll(filterDanmakus(danmakus))
        danmakuPool.sortBy { it.showAtTime }
    }

    /**
     * 追加弹幕数据（播放中调用）
     */
    fun appendData(newDanmakus: List<BaseDanmakuData>) {
        val filtered = filterDanmakus(newDanmakus)
        danmakuPool.addAll(filtered)
        danmakuPool.sortBy { it.showAtTime }
    }

    /**
     * 根据当前视频进度获取要显示的弹幕
     */
    fun getDanmakusForProgress(currentTime: Long): List<BaseDanmakuData> {
        val remainingTime = videoDurationMs - currentTime
        return danmakuPool.filter { item ->
            !displayedIds.contains(item.id) &&
                    item.showAtTime in currentTime..(currentTime + windowMs) &&
                    estimateDisplayTime(item.content ?: "") <= remainingTime
        }.also { toDisplay ->
            displayedIds.addAll(toDisplay.map { it.id })
        }
    }

    /**
     * 快进/后退时调用
     */
    fun onSeek(newTime: Long) {
        displayedIds.clear()
    }

    /**
     * 过滤非法或显示不完的弹幕
     */
    private fun filterDanmakus(source: List<BaseDanmakuData>): List<BaseDanmakuData> {
        return source.filter { item ->
            if (item.showAtTime < 0 || item.showAtTime > videoDurationMs) return@filter false
            val displayTime = item.content?.let { estimateDisplayTime(it) }
            if (item.showAtTime + displayTime!! > videoDurationMs) return@filter false
            true
        }
    }

    /**
     * 估算弹幕显示时间（可调节）
     */
    private fun estimateDisplayTime(text: String): Long {
        val baseTime = 4000L // 最短 4 秒
        val extraPerChar = 150L // 每个字符额外 150ms
        return baseTime + text.length * extraPerChar
    }
}